package com.lebang.common.push;

import com.alibaba.fastjson.JSONObject;
import com.lebang.common.utils.OkHttpUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Component
public class PushClient {


    @Value("${info.umeng.app-key}")
    private String umengAppKey;
    @Value("${info.umeng.app-master-secret}")
    private String umengAppSecret;
    @Value("${info.umeng.mi-activity}")
    private String umengMiActivity;
    @Value("${info.umeng.c-app-key}")
    private String umengCAppKey;
    @Value("${info.umeng.c-app-master-secret}")
    private String umengCAppSecret;
    @Value("${info.umeng.c-send}")
    private Boolean isSend;

    private static final Logger log = LoggerFactory.getLogger(PushClient.class);
    // The user agent
    private final String USER_AGENT = "Mozilla/5.0";

    // This object is used for sending the post request to Umeng
    protected HttpClient client = HttpClientBuilder.create().build();
    // The host
    private static final String UMENG_HOST = "http://msg.umeng.com";

    // The upload path
    private static final String UPLOAD_PATH = "/upload";

    // The post path
    private static final String POST_PATH = "/api/send";




    /**
     * @param title    标题
     * @param desc     内容
     * @param memberId 用户id
     *                 多个用,隔开
     *                 例如 "sadasd,21312,dasdas"
     * @return
     * @throws IOException
     */
    @Async
    public void sendByPushModel(String title, String desc, String memberId)  {
        String Joson = "{\n" +
                "\t\"policy\": {\n" +
                "\t\t\"expire_time\": \"" + LocalDateTime.now().plusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + "\"\n" +
                "\t},\n" +
                "\t\"description\": \"" + title + "\",\n" +
                "\t\"production_mode\": true,\n" +
                "\t\"appkey\": \"" + umengAppKey + "\",\n" +
                "\t\"payload\": {\n" +
                "\t\t\"body\": {\n" +
                "\t\t\t\"title\": \"" + title + "\",\n" +
                "\t\t\t\"ticker\": \"" + title + ":" + desc + "\",\n" +
                "\t\t\t\"text\": \"" + desc + "\",\n" +
                "\t\t\t\"after_open\": \"go_app\",\n" +
                "\t\t\t\"play_vibrate\": \"true\",\n" +
                "\t\t\t\"play_lights\": \"true\",\n" +
                "\t\t\t\"play_sound\": \"true\"\n" +
                "\t\t},\n" +
                "\t\t\"display_type\": \"notification\"\n" +
                "\t},\n" +
                "\t\"mipush\": true,\n" +
                "\t\"mi_activity\": \"" + umengMiActivity + "\",\n" +
                "\t\"alias\": \"" + memberId + "\",\n" +
                "\t\"alias_type\": \"xy\",\n" +
                "\t\"type\": \"customizedcast\",\n" +
                "\t\"timestamp\": \"" + System.currentTimeMillis() + "\"\n" +
                "}";
        String url = UMENG_HOST + POST_PATH;
        String postBody = Joson;
        String sign = null;
        try {
            sign = DigestUtils.md5Hex(("POST" + url + postBody + umengAppSecret).getBytes("utf8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();

        }
        url = url + "?sign=" + sign;
        JSONObject jsonObject=OkHttpUtil.postRequestJson(url,postBody);
        if (jsonObject != null) {
            //log.info("推送成功!");
        } else {
            log.info("推送失败");
        }
//        HttpPost post = new HttpPost(url);
//        post.setHeader("User-Agent", USER_AGENT);
//        StringEntity se = new StringEntity(postBody, "UTF-8");
//        post.setEntity(se);
//        // Send the post request and get the response
//        HttpResponse response = null;
//        try {
//            response = client.execute(post);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        int status = response.getStatusLine().getStatusCode();
//        BufferedReader rd = null;
//        try {
//            rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        StringBuilder result = new StringBuilder();
//        String line = "";
//        while (true) {
//            try {
//                if (!((line = rd.readLine()) != null)) {
//                    break;
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            result.append(line);
//        }
//        if (status == 200) {
//
//        } else {
//            log.info("推送失败");
//        }

    }




    @Async
    public void sendNoRead(String title, String desc, String memberId) {

        String Joson = "{\n" +
                "\t\"appkey\": \"" + umengAppKey + "\",\n" +
                "\t\"timestamp\": \"" + System.currentTimeMillis() + "\",\n" +
                "\t\"type\": \"customizedcast\",\n" +
                "\t\"device_tokens\": \"listcast\",\n" +
                "\t\"alias_type\": \"xy\",\n" +
                "\t\"alias\": \"" + memberId + "\",\n" +
                "\t\"payload\": {\n" +
                "\t\t\"display_type\": \"notification\",\n" +
                "\t\t\"body\": {\n" +
                "\t\t\t\"ticker\": \"" + title + "\",\n" +
                "\t\t\t\"title\": \"" + title + "\",\n" +
                "\t\t\t\"text\": \"" + desc + "\",\n" +
                "\t\t\t\"play_vibrate\": \"true\",\n" +
                "\t\t\t\"play_lights\": \"true\",\n" +
                "\t\t\t\"play_sound\": \"true\",\n" +
                "\n" +
                "\t\t\t\"after_open\": \"go_custom\",\n" +
                "\n" +
                "\t\t\t\"custom\": {\n" +
                "\t\t\t\"read\":\"false\"\n" +
                "\t\t\t}" +
                "\t\t}\n" +
                "\t},\n" +
                "\t\"production_mode\": \"true\",\n" +
                "\t\"description\": \"" + title + "\",\n" +
                "\t\"mipush\": \"true\",\n" +
                "\t\"mi_activity\": \"" + umengMiActivity + "\"\n" +
                "}";
        String url = UMENG_HOST + POST_PATH;
        String postBody = Joson;
        String sign = null;
        try {
            sign = DigestUtils.md5Hex(("POST" + url + postBody + umengAppSecret).getBytes("utf8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        url = url + "?sign=" + sign;
        JSONObject jsonObject=OkHttpUtil.postRequestJson(url,postBody);
        if (jsonObject != null) {
            //log.info("推送成功!");
        } else {
            log.info("推送失败");
        }
    }
    @Async
    public void sendTask(String title, String text, String userList) {
        if (isSend) {
            String Joson = "{\n" +
                    "\t\"appkey\": \"" + umengCAppKey + "\",\n" +
                    "\t\"timestamp\": \"" + System.currentTimeMillis() + "\",\n" +
                    "\t\"type\": \"customizedcast\",\n" +
                    "\t\"device_tokens\": \"listcast\",\n" +
                    "\t\"alias_type\": \"xysh\",\n" +
                    "\t\"alias\": \"" + userList + "\",\n" +
                    "\t\"payload\": {\n" +
                    "\t\t\"display_type\": \"notification\",\n" +
                    "\t\t\"body\": {\n" +
                    "\t\t\t\"ticker\": \"" + title + "\",\n" +
                    "\t\t\t\"title\": \"" + title + "\",\n" +
                    "\t\t\t\"text\": \"" + text + "\",\n" +
                    "\t\t\t\"play_vibrate\": \"true\",\n" +
                    "\t\t\t\"play_lights\": \"true\",\n" +
                    "\t\t\t\"play_sound\": \"true\",\n" +
                    "\n" +
                    "\t\t\t\"after_open\": \"go_app\",\n" +
                    "\n" +
                    "\t\t\t\"custom\": {\n" +
                    "\t\t\t\"read\":\"false\"\n" +
                    "\t\t\t}" +
                    "\t\t}\n" +
                    "\t},\n" +
                    "\t\"production_mode\": \"true\",\n" +
                    "\t\"description\": \"" + text + "\",\n" +
                    "}";
            String url = UMENG_HOST + POST_PATH;
            String postBody = Joson;
            String sign = null;
            sign = DigestUtils.md5Hex(("POST" + url + postBody + umengCAppSecret).getBytes(StandardCharsets.UTF_8));
            url = url + "?sign=" + sign;
//            HttpPost post = new HttpPost(url);
//            post.setHeader("User-Agent", USER_AGENT);
//            StringEntity se = new StringEntity(postBody, "UTF-8");
//            post.setEntity(se);
//            // Send the post request and get the response
//            HttpResponse response = null;
//            try {
//                response = client.execute(post);
//            } catch (IOException e) {
//                log.info("推送失败");
//                e.printStackTrace();
//                return;
//            }
//            int status = response.getStatusLine().getStatusCode();
//            //log.info("Response Code : " + status);
//            BufferedReader rd = null;
//            try {
//                rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            StringBuilder result = new StringBuilder();
//            String line = "";
//            while (true) {
//                try {
//                    if (rd == null || (line = rd.readLine()) == null) {
//                        break;
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                result.append(line);
//            }
//          //  log.info(result.toString() + line + "________" + Arrays.toString(umengCAppSecret.getBytes(StandardCharsets.UTF_8)));
//            if (status == 200) {
//            //    //log.info("推送成功!");
//            } else {
//             //   log.info("推送失败");
//            }
            JSONObject jsonObject=OkHttpUtil.postRequestJson(url,postBody);
            if (jsonObject != null) {
                //log.info("推送成功!");
            } else {
                log.info("推送失败");
            }
       }

    }
}
